package com.attunlcok.unlock.service.impl;

import com.attunlcok.common.core.text.Convert;
import com.attunlcok.common.utils.DateUtils;
import com.attunlcok.common.utils.StringUtils;
import com.attunlcok.unlock.domain.AttEmailInfo;
import com.attunlcok.unlock.mapper.AttEmailInfoMapper;
import com.attunlcok.unlock.service.IAttEmailInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ATT邮箱信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-05
 */
@Service
public class AttEmailInfoServiceImpl implements IAttEmailInfoService
{
    @Autowired
    private AttEmailInfoMapper attEmailInfoMapper;

    /**
     * 查询ATT邮箱信息
     * 
     * @param id ATT邮箱信息主键
     * @return ATT邮箱信息
     */
    @Override
    public AttEmailInfo selectAttEmailInfoById(Long id)
    {
        return attEmailInfoMapper.selectAttEmailInfoById(id);
    }

    /**
     * 查询ATT邮箱信息列表
     * 
     * @param attEmailInfo ATT邮箱信息
     * @return ATT邮箱信息
     */
    @Override
    public List<AttEmailInfo> selectAttEmailInfoList(AttEmailInfo attEmailInfo)
    {
        return attEmailInfoMapper.selectAttEmailInfoList(attEmailInfo);
    }

    /**
     * 新增ATT邮箱信息
     * 
     * @param attEmailInfo ATT邮箱信息
     * @return 结果
     */
    @Override
    public int insertAttEmailInfo(AttEmailInfo attEmailInfo)
    {
        attEmailInfo.setCreateTime(DateUtils.getNowDate());
        return attEmailInfoMapper.insertAttEmailInfo(attEmailInfo);
    }

    /**
     * 修改ATT邮箱信息
     * 
     * @param attEmailInfo ATT邮箱信息
     * @return 结果
     */
    @Override
    public int updateAttEmailInfo(AttEmailInfo attEmailInfo)
    {
        attEmailInfo.setUpdateTime(DateUtils.getNowDate());
        return attEmailInfoMapper.updateAttEmailInfo(attEmailInfo);
    }

    /**
     * 批量删除ATT邮箱信息
     * 
     * @param ids 需要删除的ATT邮箱信息主键
     * @return 结果
     */
    @Override
    public int deleteAttEmailInfoByIds(String ids)
    {
        return attEmailInfoMapper.deleteAttEmailInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除ATT邮箱信息信息
     * 
     * @param id ATT邮箱信息主键
     * @return 结果
     */
    @Override
    public int deleteAttEmailInfoById(Long id)
    {
        return attEmailInfoMapper.deleteAttEmailInfoById(id);
    }

    /**
     * 导入邮箱数据
     * 
     * @param emailData 邮箱数据字符串，每行一个邮箱
     * @param operName 操作人
     * @return 导入结果信息
     */
    @Override
    @Transactional
    public String importEmailData(String emailData, String operName)
    {
        if (StringUtils.isEmpty(emailData))
        {
            return "导入数据不能为空！";
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        String[] lines = emailData.split("\\r?\\n");
        Date now = DateUtils.getNowDate();

        for (String line : lines)
        {
            try
            {
                if (StringUtils.isEmpty(line))
                {
                    continue;
                }

                // 解析邮箱和密码
                String[] parts = line.split("---");
                String email = parts[0].trim();
                String password = parts.length > 1 ? parts[1].trim() : null;

                // 检查邮箱格式
                if (!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$"))
                {
                    failureNum++;
                    failureMsg.append("<br/>第 " + (successNum + failureNum) + " 行邮箱格式不正确：" + email);
                    continue;
                }

                // 检查邮箱是否已存在
                AttEmailInfo checkInfo = new AttEmailInfo();
                checkInfo.setEmail(email);
                List<AttEmailInfo> existList = attEmailInfoMapper.selectAttEmailInfoList(checkInfo);
                if (!existList.isEmpty())
                {
                    failureNum++;
                    failureMsg.append("<br/>第 " + (successNum + failureNum) + " 行邮箱已存在：" + email);
                    continue;
                }

                // 创建新的邮箱信息
                AttEmailInfo emailInfo = new AttEmailInfo();
                emailInfo.setEmail(email);
                emailInfo.setPassword(password);
                emailInfo.setIsUsed("0");
                emailInfo.setUsedCount(0L);
                emailInfo.setStatus("0");
                emailInfo.setCreateBy(operName);
                emailInfo.setCreateTime(now);

                attEmailInfoMapper.insertAttEmailInfo(emailInfo);
                successNum++;
                successMsg.append("<br/>第 " + (successNum + failureNum) + " 行导入成功：" + email);
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>第 " + (successNum + failureNum) + " 行导入失败：" + e.getMessage();
                failureMsg.append(msg);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
